-- ShopM
-- Create by panyl
-- 商铺模块

module("ShopM", package.seeall);

-- 配置
local ruleTable = {};

-- 所有的商品信息
local goodsTable = {};

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    -- 转换下信息表
    ruleTable = {};
    goodsTable = {};

    local shop_rule_CSV = get_shop_rule_CSV();
    for i = 1, #shop_rule_CSV do
        ruleTable[shop_rule_CSV[i].id] = shop_rule_CSV[i];
    end

    -- 转换下shop_goods配置表
    local shop_goods_CSV = get_shop_goods_CSV();
    for i = 1, #shop_goods_CSV do
        -- 解析出商品信息
        goodsTable[shop_goods_CSV[i].id] = parseGoods(shop_goods_CSV[i])
    end

    shop_goods_CSV = {};
end

-- 模块初始化
function init()
    loadCsv();
end

-- 解析商品数据
function parseGoods(info)
    -- 商品
    local arr = string.explode(string.sub(info.goods, 3, -2), ",");
    if string.startWith(info.goods, "1(") then
        info.goods = { 1, tonumber(arr[1]), tonumber(arr[2]), };
    elseif string.startWith(info.goods, "6(") then
        info.goods = { 6, tonumber(arr[1]), tonumber(arr[2]), };
    else
        info.goods = { 8, tonumber(arr[1]), tonumber(arr[2]), };
    end

    -- 价格
    local ret = {}
    local prices = string.explode(info.price, "|")
    for index, price in pairs(prices) do
        -- 每个价格都是price1 + price2 + .. 这个格式的
        ret[index] = {}
        local desc = string.explode(price, "+")
        for i = 1, #desc do
            arr = string.explode(string.sub(desc[i], 3, -2), ",");
            if string.startWith(desc[i], "1(") then
                -- 物品
                ret[index][i] = { 1, tonumber(arr[1]), tonumber(arr[2]), }
            elseif string.startWith(desc[i], "2(") then
                -- 属性
                ret[index][i] = { 2, arr[1], tonumber(arr[2]), }
            else
                -- 秘宝
                ret[index][i] = { 6, tonumber(arr[1]), tonumber(arr[2]), }
            end
        end
    end

    info.price = ret;

    return info
end

-- 获取商品
function queryGoodsInfo(goodsId)
    -- 返回商品
    return goodsTable[goodsId].goods
end

-- 获取商品类别
function queryClassify(goodsId)
    -- 返回商品
    return goodsTable[goodsId].classify
end

-- 检索商品价格
function queryPrice(goodsId, index)
    local m = goodsTable[goodsId].price

    if not m or #m <= index then
        return nil
    end

    return m[index + 1][1]
end

-- 检索
function query(id, path)
    local m = ruleTable[id];

    if not m or not path then
        return m;
    end

    return m[path];
end

-- 获取商店信息
function getShopData(shopType)
    local shopInfo = ME.user.dbase:query("shopData", {});

    if not shopType then
        return shopInfo;
    end

    return shopInfo[shopType];
end

-- 判断能否购买物品，只判断价格
function canBuyGoods(shopType, goodsIndex)
    local info = getShopData(shopType);

    local goodsInfo = info.goods[goodsIndex];
    -- 没有该商店信息
    if not info or not goodsInfo then
        return false
    end

    -- 如果已经买过了
    if goodsInfo.sold_out then
        return "sold_out"   -- 商品已售完
    end


    local priceIndex = goodsInfo.price;
    local goodsId = info.goods[goodsIndex].goods_id;
    local arr;
    if goodsInfo.goods_type == "honor_scrap" then
        arr = parseGoodsPrice(priceIndex);
    else
        arr = queryPrice(goodsId, priceIndex);
    end
    local ok = true;

    if arr[1] == 1 then
        -- 物品
        ok = ItemM.getAmount(ME.user, arr[2]) >= arr[3]
        if not ok then
            return string.format("item_%d_lack", arr[2]), arr[3];  -- 物品数量不足
        end
    elseif arr[1] == 2 then
        -- 属性
        ok = ME.user.dbase:query(arr[2], 0) >= arr[3]
        if not ok then
            return arr[2] .. "_lack", arr[3];  -- 属性数量不足
        end
    else
        return false
    end

    return ok
end

-- 判断能否刷新商品
function canRefreshGoods(shopType)
    local ok = true;
    local cost = FormulaM.invoke("CALC_SHOP_REFRESH_COST", ME.user, shopType, getShopRefreshCount(shopType));
    for _, arr in pairs(cost) do
        if arr[1] == 2 then
            ok = ME.user.dbase:query(arr[2], 0) >= arr[3];
        end

        if true ~= ok then
            return "cost_lack";
        end
    end

    return ok;
end

-- 获取商店手动刷新次数
function getShopRefreshCount(shopType)
    local shopInfo = getShopData(shopType);
    if shopInfo ~= nil and shopInfo.refresh_count ~= nil then
        return shopInfo.refresh_count;
    end

    return 0;
end

-- 获取商店自动刷新时间
function getShopAutoRefreshTime(shopType)
    local shopInfo = getShopData(shopType);
    if shopInfo ~= nil and shopInfo.auto_refresh_time ~= nil then
        return shopInfo.auto_refresh_time;
    end

    return 0;
end

-- 商店刷新剩余时间
function getShopAutoRefreshLeftTime(shopType)
    local shopInfo = getShopData(shopType);
    local serverTime = TimeM.getServerTime();
    if shopInfo ~= nil and shopInfo.auto_refresh_time ~= nil then
        return shopInfo.auto_refresh_time - serverTime;
    end

    return 0;
end

-- 获取商店商品
function getAllGoods(shopType)
    local shopInfo = getShopData(shopType);
    local list = {};
    if shopInfo == nil or shopInfo.goods == nil then
        return {};
    end

    -- 按照位置升序
    local indexList = table.keys(shopInfo.goods);
    table.sort(indexList);

    for _, index in pairs(indexList) do
        local info = shopInfo.goods[index];
        table.insert(list, info);
    end

    return list;
end

-- 根据索引获得商店出售物品信息
function getGoodInfoInShop(shopType, goodsIndex)
    local shopInfo = getShopData(shopType);
    if shopInfo == nil then
        return nil;
    end

    return shopInfo.goods[goodsIndex];
end

-- 购买结果
function buyGoodsResult(shopType, goodsIndex, result)
    local temp = ME.user.buy_goods_temp or {};
    local arr = temp[1];

    table.remove(temp, 1);

    -- 如果没有购买成功
    if 1 ~= result then
        -- 需要把消耗补充回来，按顺序来就行了
        if arr and sizeof(arr) == 3 then
            BonusM.doBonus(arr);
        end
        return;
    end

    local shopInfo = getShopData(shopType);
    if not shopInfo then
        return;
    end

    -- 标记为已售光
    shopInfo["goods"][goodsIndex]["sold_out"] = 1;

    -- 抛出事件
    EventMgr.fire(event.BUY_SHOP_GOODS, {["shopType"] = shopType, ["goodsIndex"] = goodsIndex, });
end

-- 取得商品信息
function parseGoodsPrice(price)
    local priceArray = price[1];
    return priceArray;
end

-- 购买
function buyGoods(shopType, goodsIndex)
    local info = getShopData(shopType);

    local goodsInfo = info.goods[goodsIndex];
    -- 没有该商店信息
    if not info or not goodsInfo then
        return false
    end

    -- 如果已经买过了
    if goodsInfo.sold_out then
        return "sold_out"   -- 商品已售完
    end


    local priceIndex = goodsInfo.price;
    local goodsId = info.goods[goodsIndex].goods_id;
    local arr;
    if goodsInfo.goods_type == "honor_scrap" then
        arr = parseGoodsPrice(priceIndex);
    else
        arr = queryPrice(goodsId, priceIndex);
    end

    -- 预先保存起来
    ME.user.buy_goods_temp = ME.user.buy_goods_temp or {};
    table.insert(ME.user.buy_goods_temp, arr);

    if arr[1] == 1 then
        -- 物品
        ItemM.costAmount(ME.user, arr[2], arr[3]);
    elseif arr[1] == 2 then
        -- 属性
        ME.user:costAttrib(arr[2], arr[3]);
    else
        return false
    end

    return true;
end
